var laypage, frame;
var vm = new Vue({
	el: "#info",
	data: {
		load:  false,
		error: false,
		beans: [],
		page:  0,
		count: 0,
		rows:  10,
	},
	methods: {
		edit: function(index) {
			var height = $("#BODY_FRAME", parent.document).height() - 80;
			if(height > 820) height = 820;
			var url = "add.html";
			if(index != -1) {
				url = 'add.html?id=' + vm.beans[index].id + "&index=" + index;
			}
			frame = layer.open({
			  type: 2,
			  area: ['850px', height + 'px'],
			  title: false,
			  closeBtn: 1,
			  shadeClose: true,
			  skin: 'layui-layer-lan',
			  content: url
			});
		}, del: function(index) {
			var id = vm.beans[index].id;
			layer.confirm('确定要删除ID为[' + id + ']的信息吗？', {
				title : '删除?',
				btn : [ '确定', '取消' ]
			}, function() {
				$.post("delete.json", {"id" : id}, function(res){
					if(res.code != 0){
						layer.msg(res.message, {icon : 2});
					}else{
						layer.msg("删除成功!", {icon : 1});
						reflush();
					}
				});
			});
		}
	},
	computed: {
		max: function(){
			return parseInt(this.count / this.rows + (this.count % this.rows == 0 ? 0 : 1));
		}
	}
});

function reloadBean(index, bean) {
	if(index != -1) {
		layer.msg("提交成功!", {icon : 1});
		vm.beans[index].title    = bean.title;
		vm.beans[index].pubTime  = bean.pubTime;
		vm.beans[index].pubMedia = bean.pubMedia;
		vm.beans[index].summary  = bean.summary;
		vm.beans[index].hit      = bean.hit;
	} else {
		reflush();
	}
	layer.close(frame);
}

function reflush() {
	loadBean(vm.page);
}

function reload(page) {
	if(page != vm.page) {
		loadBean(page);
	}
}

function loadBean(curr) {
	vm.load = false;
	vm.error = false;
	var data = { "page" : curr };
	$.post("list.json", data).done(function(res){
		if(res.code == 0) {
			vm.beans = res.message.beans;
			vm.page = res.message.page;
			vm.count = res.message.count;
			if(vm.load) vm.load = true;
			laypage({
				cont: 'page',
				curr: vm.page,
				pages: vm.max,
				skip: true,
				prev: false,
				next: false,
				jump: function(obj, first){
					reload(obj.curr);
				}
			});
		}
	}).fail(function(err){
		vm.error = true;
	});
}

layui.use(['laypage', 'form'], function(){
	laypage = layui.laypage;
	loadBean(1);
});